package com.renzh.gateway.fiflt;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 网关鉴权
 */
@Component
public class AuthFilter implements GlobalFilter{

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        System.out.println("鉴权开始...");
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        if(queryParams.containsKey("token")){
            List<String> token = queryParams.get("token");
            if(!"123456".equals(token.get(0))){
                ServerHttpResponse response = exchange.getResponse();
                URI uri = request.getURI();
                System.out.println("请求的地址是："+ uri.getPath());
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                response.getHeaders().add("Content-type","application/json");
                DataBuffer wrap = response.bufferFactory().wrap("没有权限访问！".getBytes(StandardCharsets.UTF_8));
                return response.writeWith(Mono.just(wrap));
            }
        }
        return chain.filter(exchange);
    }
}